﻿using Aspose.Words;
using Aspose.Words.MailMerging;
using System;
using System.Collections.Generic;
using System.IO;

namespace QuickFill.Services
{
    public class MergeService
    {
        public void MergeDocument(string templatePath, string outputPath, Dictionary<string, object> data)
        {
            try
            {
                // 确保输出目录存在
                Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

                // 加载模板文档
                Document doc = new Document(templatePath);

                // 设置邮件合并事件处理
                doc.MailMerge.FieldMergingCallback = new HandleMergeField();

                // 执行邮件合并
                doc.MailMerge.Execute(
                    GetFieldNames(data),
                    GetFieldValues(data));

                // 保存文档
                doc.Save(outputPath);
            }
            catch (Exception ex)
            {
                throw new Exception($"处理文档失败: {Path.GetFileName(templatePath)}\n{ex.Message}");
            }
        }

        private string[] GetFieldNames(Dictionary<string, object> data)
        {
            var names = new string[data.Count];
            data.Keys.CopyTo(names, 0);
            return names;
        }

        private object[] GetFieldValues(Dictionary<string, object> data)
        {
            var values = new object[data.Count];
            data.Values.CopyTo(values, 0);
            return values;
        }

        private class HandleMergeField : IFieldMergingCallback
        {
            public void FieldMerging(FieldMergingArgs args)
            {
                // 可以在此处添加自定义合并逻辑
                // 例如，格式化日期、数字等
            }

            public void ImageFieldMerging(ImageFieldMergingArgs args)
            {
                // 图片合并处理
                // 如果需要支持图片合并，可以在此实现
            }
        }
    }
}